<template>
  <div>
    <div v-for="item in data.articleList" :key="item.id">
      <div class="item">
        <div class="item_id">编号：{{ item.id }}</div>
        <div class="item_content">内容：{{ item.content }}</div>
        <div>{{ item }}</div>
        <img v-if="item.isLike===0" @click="handleLike(item.id)" src="../assets/未点赞.png" class="item_img" alt="图片">
        <img v-else @click="handleLike(item.id)" src="../assets/点赞.png" class="item_img" alt="图片">
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import axios from "axios";
import {reactive} from "vue";
import {ElMessage} from "element-plus";

const data = reactive({
  articleList: [] as Article[],//所有内容列表
  userLikeList: [] as any[]//当前用户点赞表的数据
})

interface GiveALike {
  articleId: number,
  userId: number
}

interface Article {
  id: number,
  content: string,
  isLike?: number
}

//点赞所需的参数
const giveALikeParam = reactive<GiveALike>({
  articleId: 0,//文章编号
  userId: 0//用户编号
})

//获取所有内容
const getList = () => {
  axios.get("http://localhost:5000/giveALike/getList").then((res) => {
    data.articleList = res.data
    console.log(res.data)
  })
}

//点赞
const handleLike = (row: number) => {
  //从session中获取用户信息
  const user = JSON.parse(window.sessionStorage.getItem("user") ?? '')
  //设置用户编号
  giveALikeParam.userId = user.id
  //设置文章编号
  giveALikeParam.articleId = row
  axios.post("http://localhost:5000/giveALike/saveUserLike", giveALikeParam).then((res) => {
    data.articleList[row - 1].isLike = data.articleList[row - 1].isLike === 1 ? 0 : 1;
    if (res.data.isLike == 1) {
      ElMessage({
        message: '点赞成功',
        type: 'success',
      })
    } else {
      ElMessage({
        message: '取消点赞',
        type: 'warning',
      })
    }
  })
}

getList()
</script>

<style lang="less" scoped>
.item {
  display: flex;

  .item_id {
    margin-right: 10px;
  }

  .item_content {
    width: 100px;
  }

  .item_img {
    width: 100px;
    height: 100px;
    cursor: pointer;
  }
}
</style>